BUILD:=../build
SRC:= .

ENTERPOINT := 0x10000 # 内核开始执行的位置，看007.md内存布局，在0x7E00~0x9FBFF中随便选了一个地址

CFLAGS:= -m32 		  # 32位的程序
CFLAGS+= -fno-builtin # 不需要gcc的内置函数
CFLAGS+= -nostdinc    # 不需要标准头文件
CFLAGS+= -fno-pic     # 不需要位置无关的代码 position independent code
CFLAGS+= -fno-pie     # 不需要位置无关的可执行程序 position independent executable
CFLAGS+= -fno-stack-protector # 不需要栈保护
CFLAGS:=$(strip ${CFLAGS})    # 将CFLAGS中的\t全部去掉

DEBUG:= -g
INCLUDE:=-I$(SRC)/include

$(BUILD)/boot/%.bin: $(SRC)/boot/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f bin $< -o $@

$(BUILD)/kernel/%.o: $(SRC)/kernel/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f elf32 $(DEBUG) $< -o $@

$(BUILD)/kernel/%.o: $(SRC)/kernel/%.c
	$(shell mkdir -p $(dir $@))
	gcc $(CFLAGS) $(DEBUG) $(INCLUDE) -c  $< -o $@

$(BUILD)/kernel.bin: $(BUILD)/kernel/start.o \
	$(BUILD)/kernel/main.o

	$(shell mkdir -p $(dir $@))
	ld -m elf_i386 -static $^ -o $@ -Ttext $(ENTERPOINT)

$(BUILD)/system.bin: $(BUILD)/kernel.bin # 将.bss段展开到文件中，loader 加载内核更方便
	objcopy -O binary $< $@   

$(BUILD)/system.map: $(BUILD)/kernel.bin
	nm $< | sort > $@

$(BUILD)/master.img: $(BUILD)/boot/boot.bin	$(BUILD)/boot/loader.bin $(BUILD)/system.bin $(BUILD)/system.map 

	yes | bximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat $@
	dd if=$(BUILD)/boot/boot.bin of=$@ bs=512 count=1 conv=notrunc
	dd if=$(BUILD)/boot/loader.bin of=$@ bs=512 count=4 seek=2 conv=notrunc # seek从第2个扇区开始,写入4个扇区
	dd if=$(BUILD)/system.bin of=$@ bs=512 count=200 seek=10 conv=notrunc

# .PHONY: usb
# usb: boot.bin /dev/sdb
# 	sudo dd if=/dev/sdb of=tmp.bin bs=512 count=1 conv=notrunc
# 	cp tmp.bin usb.bin
# 	sudo rm tmp.bin
# 	dd if=boot.bin of=usb.bin bs=446 count=1 conv=notrunc
# 	sudo dd if=usb.bin of=/dev/sdb bs=512 count=1 conv=notrunc
# 	rm usb.bin

test: $(BUILD)/master.img

.PHONY: clean
clean:
	rm -rf $(BUILD)

.PHONY: bochs
bochs:$(BUILD)/master.img
	bochs -q -f ../bochs/bochsrc

.PHONY: bochsg
bochsg:$(BUILD)/master.img
	bochs-gdb -q -f ../bochs/bochsrc.gdb

.PHONY: qemu
qemu:$(BUILD)/master.img
	qemu-system-i386 \
	-m 32M \
	-boot c \
	-hda $<

.PHONY: qemug
qemug:$(BUILD)/master.img
	qemu-system-i386 \
	-s -S \
	-m 32M \
	-boot c \
	-hda $<

$(BUILD)/master.vmdk:$(BUILD)/master.img
	qemu-img convert -O vmdk $< $@

.PHONY:vmdk
vmdk:$(BUILD)/master.vmdk